/*
 * Copyright (C) 2015 Kenji Le
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package glamourbeautyclinic.personel;

import images.GlamourImage;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import util.DBConnection;

/**
 *
 * @author Kenji Le
 */
public class dlgSpecialist extends javax.swing.JDialog {

    GlamourImage GI = new GlamourImage();
    FrmStaff_Hung staff;
    Statement stmt;
    ResultSet rs;
    String sql;
    DefaultListModel<String> specModel_dlg;
    DefaultListModel<String> transferModel;
    DefaultListModel tempModel;
    DefaultListModel service;
    DefaultListModel cate;
    String EmpID;

    /**
     * Creates new form dlgSpecialist
     */
    public dlgSpecialist(java.awt.Frame parent, boolean modal, DefaultListModel specialist, String emp,String name, DBConnection dc) {
        super(parent, modal);
        initComponents();
        this.setTitle("Specialist of "+ name);
        GI.addIconFor(this);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // Can be resize height parameter to proper scale
        this.setLocation((screenSize.width - this.getWidth()) / 2, (screenSize.height - this.getHeight() - 60) / 2);

        transferModel = specialist;
        EmpID = emp;
        tempModel = new DefaultListModel<>();
        specModel_dlg = new DefaultListModel<>();
        for (int i = 0; i < specialist.size(); i++) {
            tempModel.addElement((String) specialist.get(i));
            specModel_dlg.addElement((String) specialist.get(i));
        }
        lstSpec_dlg.setModel(specModel_dlg);
        //
        staff = new FrmStaff_Hung(dc);

        try {
            stmt = dc.con.createStatement();
            //Add value to category List
            sql = "select * from Category";
            rs = stmt.executeQuery(sql);
            cate = new DefaultListModel();
            while (rs.next()) {
                cate.addElement(rs.getString(2));
            }
            lstCat.setModel(cate);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void beginState() {
        lstSer.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlSpec = new javax.swing.JPanel();
        lblCat = new javax.swing.JLabel();
        jspCat = new javax.swing.JScrollPane();
        lstCat = new javax.swing.JList();
        lblSer = new javax.swing.JLabel();
        jspSer = new javax.swing.JScrollPane();
        lstSer = new javax.swing.JList();
        lblSpec = new javax.swing.JLabel();
        jspSpec = new javax.swing.JScrollPane();
        lstSpec_dlg = new javax.swing.JList();
        btnSubmit = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Specialist");
        setAlwaysOnTop(true);
        setModal(true);

        lblCat.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblCat.setForeground(new java.awt.Color(0, 51, 255));
        lblCat.setText("Category");

        lstCat.setForeground(new java.awt.Color(0, 102, 51));
        lstCat.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstCat.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                lstCatMousePressed(evt);
            }
        });
        jspCat.setViewportView(lstCat);

        lblSer.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblSer.setForeground(new java.awt.Color(0, 51, 255));
        lblSer.setText("Available service");

        lstSer.setForeground(new java.awt.Color(0, 102, 51));
        lstSer.setToolTipText("");
        jspSer.setViewportView(lstSer);

        lblSpec.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblSpec.setForeground(new java.awt.Color(0, 51, 255));
        lblSpec.setText("Employee's specialist");

        lstSpec_dlg.setForeground(new java.awt.Color(0, 102, 51));
        jspSpec.setViewportView(lstSpec_dlg);

        btnSubmit.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnSubmit.setForeground(new java.awt.Color(0, 51, 51));
        btnSubmit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Select.png"))); // NOI18N
        btnSubmit.setText("Submit");
        btnSubmit.setBorderPainted(false);
        btnSubmit.setContentAreaFilled(false);
        btnSubmit.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        btnCancel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Cancel.png"))); // NOI18N
        btnCancel.setText("Cancel");
        btnCancel.setBorderPainted(false);
        btnCancel.setContentAreaFilled(false);
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/001_25.png"))); // NOI18N
        btnAdd.setBorderPainted(false);
        btnAdd.setContentAreaFilled(false);
        btnAdd.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/001_27.png"))); // NOI18N
        btnRemove.setBorderPainted(false);
        btnRemove.setContentAreaFilled(false);
        btnRemove.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlSpecLayout = new javax.swing.GroupLayout(pnlSpec);
        pnlSpec.setLayout(pnlSpecLayout);
        pnlSpecLayout.setHorizontalGroup(
            pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSpecLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jspCat, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCat))
                .addGap(10, 10, 10)
                .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlSpecLayout.createSequentialGroup()
                        .addComponent(jspSer, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(lblSer))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, 11, Short.MAX_VALUE)
                .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jspSpec, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblSpec))
                .addContainerGap())
            .addGroup(pnlSpecLayout.createSequentialGroup()
                .addGap(160, 160, 160)
                .addComponent(btnSubmit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pnlSpecLayout.setVerticalGroup(
            pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSpecLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblSer, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblCat)
                        .addComponent(lblSpec)))
                .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlSpecLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jspSer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jspCat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jspSpec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(pnlSpecLayout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(pnlSpecLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(btnSubmit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnCancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlSpec, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlSpec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
        ArrayList<String> removedItems = new ArrayList<>();
        ArrayList<String> newItems = new ArrayList<>();
        // Add value to newItems
        for (int i = 0; i < lstSpec_dlg.getModel().getSize(); i++) {
            boolean isFind = false;
            for (int j = 0; j < tempModel.getSize(); j++) {
                if (specModel_dlg.get(i).equals(tempModel.get(j))) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                newItems.add(specModel_dlg.get(i));
            }
        }
        // Add value to removedItems
        for (int i = 0; i < tempModel.getSize(); i++) {
            boolean isFind = false;
            for (int j = 0; j < specModel_dlg.getSize(); j++) {
                if (specModel_dlg.get(j).equals(tempModel.get(i))) {
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                removedItems.add((String) tempModel.get(i));
            }
        }
        // Replace Items name with service ID
        try {
            rs = stmt.executeQuery("select * from services");
            while (rs.next()) {
                for (int i = 0; i < removedItems.size(); i++) {
                    if (rs.getString("ServiceName").equalsIgnoreCase(removedItems.get(i))) {
                        removedItems.set(i, rs.getString(1));
                    }
                }
                for (int i = 0; i < newItems.size(); i++) {
                    if (rs.getString("ServiceName").equalsIgnoreCase(newItems.get(i))) {
                        newItems.set(i, rs.getString(1));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Delete removedItems, and add newItem to database
        try {
            for (int i = 0; i < removedItems.size(); i++) {
                sql = "delete from specialist where StaffID='" + EmpID + "' and ServiceID='" + removedItems.get(i) + "'";
                stmt.executeUpdate(sql);
            }
            for (int i = 0; i < newItems.size(); i++) {
                sql = "Insert into specialist(StaffID,ServiceID) values ('" + EmpID + "','" + newItems.get(i) + "')";
                stmt.executeUpdate(sql);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Add to specModel in FrmStaff
        transferModel.clear();
        for (int i = 0; i < specModel_dlg.getSize(); i++) {
            transferModel.addElement(specModel_dlg.get(i));
        }
        //
        this.setVisible(false);
        dispose();
    }//GEN-LAST:event_btnSubmitActionPerformed

    private void lstCatMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstCatMousePressed
        lstSer.setEnabled(true);
        // Add value to service List
        int line = lstCat.getSelectedIndex();
        if (line != -1) {
            try {
                sql = "select * from vw_cate_services";
                rs = stmt.executeQuery(sql);
                service = new DefaultListModel();
                while (rs.next()) {
                    if (rs.getString("CatName").equalsIgnoreCase((String) cate.get(line))) {
                        boolean isDulicate = false;
                        for (int i = 0; i < specModel_dlg.getSize(); i++) {
                            if (rs.getString("ServiceName").equalsIgnoreCase(specModel_dlg.get(i))) {
                                isDulicate = true;
                                break;
                            }
                        }
                        if (!isDulicate) {
                            service.addElement(rs.getString(3));
                        }
                    }
                }
                lstSer.setModel(service);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_lstCatMousePressed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        int line = lstSer.getSelectedIndex();
        List selectedList = lstSer.getSelectedValuesList();
        if (line != -1) {
            for (int i = 0; i < selectedList.size(); i++) {
                specModel_dlg.addElement((String) selectedList.get(i));
                service.removeElement(selectedList.get(i));
            }
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        int line = lstSpec_dlg.getSelectedIndex();
        List selectedList = lstSpec_dlg.getSelectedValuesList();
        if (line != -1) {
            try {
                rs = stmt.executeQuery("select * from vw_cate_services");
                int CateLine = lstCat.getSelectedIndex();
                ArrayList serTemp = new ArrayList();
                while (rs.next()) {
                    if (CateLine != -1) {
                        if (lstCat.getSelectedValue().equals(rs.getString(2))) {
                            serTemp.add(rs.getString(3));
                        }
                    }
                } // Get a serTemp List to compare with lstSpec_dlg
                for (int i = 0; i < selectedList.size(); i++) {
                    for (int j = 0; j < serTemp.size(); j++) {
                        if (selectedList.get(i).equals(serTemp.get(j))) {
                            boolean isDuplicate = false;
                            for (int k = 0; k < service.getSize(); k++) {
                                if (selectedList.get(i).equals(service.get(k))) {
                                    isDuplicate = true;
                                    break;
                                }
                            }
                            if (!isDuplicate) {
                                service.addElement(selectedList.get(i));
                            }

                        }
                    }
                    specModel_dlg.removeElement(selectedList.get(i));
                } // Specialists have the same name with the service in selected Category will add to service

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        specModel_dlg.clear();
        for (int i = 0; i < tempModel.size(); i++) {
            specModel_dlg.addElement((String) tempModel.get(i));
        }
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgSpecialist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgSpecialist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgSpecialist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgSpecialist.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnSubmit;
    private javax.swing.JScrollPane jspCat;
    private javax.swing.JScrollPane jspSer;
    private javax.swing.JScrollPane jspSpec;
    private javax.swing.JLabel lblCat;
    private javax.swing.JLabel lblSer;
    private javax.swing.JLabel lblSpec;
    private javax.swing.JList lstCat;
    private javax.swing.JList lstSer;
    private javax.swing.JList lstSpec_dlg;
    private javax.swing.JPanel pnlSpec;
    // End of variables declaration//GEN-END:variables
}
